package com.yksj.healthtalk.db;

import java.util.Collection;
import java.util.List;

import org.universalimageloader.utils.StorageUtils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.yksj.healthtalk.db.Tables.TableChatMessage;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.entity.NewsEntity;
import com.yksj.healthtalk.entity.VirtualDoctorEntity;

/**
 * 用户数据库基本操作
 * 
 * @author zhao
 * @version 3.0
 */
public class ChatUserDatabase extends DataBase {

	ChatUserDatabase(Context context, String name) {
		super(context, name);
	}

	/**
	 * @param 好友聊天消息保存
	 * @return 返回自增消息id
	 */
	public synchronized long saveUserChatMessage(ContentValues contentValues) {
		return userDatabase.replace(
				Tables.TableChatMessage.TABLE_CHAT_MESSAGE,
				TableChatMessage.MESSAGE_ID, 
				contentValues);
	}

	/*
	 * public long save(String string, ContentValues values, String string2,
	 * String[] strings) { return userDatabase.update(string, values, "id = ?",
	 * strings); }
	 */

	/**
	 * 
	 * 改变消息的状态
	 * 
	 * @param id
	 *            消息id
	 * @param contentValues
	 */
	public synchronized void updateChatMessageState(String id, ContentValues contentValues) {
		userDatabase.update(TableChatMessage.TABLE_CHAT_MESSAGE, contentValues,
				"message_id=?", new String[] { id });
	}

	/**
	 * 
	 * 删除本地数据库消息
	 * 
	 * @param list
	 *            消息实体
	 * @return 失败成功状态
	 * 
	 */
	public boolean deleteChatMsg(Collection<MessageEntity> list) {
		userDatabase.beginTransaction();
		try {
			for (MessageEntity messageEntity : list) {
				if (messageEntity.getType() == MessageEntity.TYPE_VOICE) {
					StorageUtils.deleteVoiceFile(messageEntity.getContent());
				} else if (messageEntity.getType() == MessageEntity.TYPE_PICTURE) {
					StorageUtils.deleteImageFile(messageEntity.getContent());
				} else if (messageEntity.getType() == MessageEntity.TYPE_LOCATION) {
					StorageUtils.deleteMapFile(messageEntity.getContent());
				}
				deleteChatMessage(messageEntity.getId());
			}
			userDatabase.setTransactionSuccessful();
		} finally {
			userDatabase.endTransaction();
		}
		return true;
	}

	/**
	 * 
	 * 删除好友聊天消息
	 * 
	 * @param messageEntity
	 * @return
	 * 
	 */
	public boolean deleteChatMessage(String id) {
		return userDatabase.delete(Tables.TableChatMessage.TABLE_CHAT_MESSAGE,
				"message_id = ?", new String[] { id }) > 0;
	}

	/**
	 * 
	 * 根据聊天者id删除所有的消息
	 * 
	 * @param id1
	 *            发送者id
	 * @param id2
	 *            接受者id
	 * @return
	 */
	public boolean deleteAllChatMessageByChatId(String id1, String id2) {
		int result = userDatabase
				.delete(TableChatMessage.TABLE_CHAT_MESSAGE,
						"(sender_id=? and receiver_id=?) or (receiver_id=? and sender_id=?)",
						new String[] { id1, id2, id1, id2 });
		return result > 0;
	}

	/**
	 * 更新消息读取状态为已读状态
	 * @param list
	 * @param i
	 * @param contentValues
	 */
	public void updateChatMessageDuQu(List<MessageEntity> list, int i,
			ContentValues contentValues) {
		userDatabase.update(Tables.TableChatMessage.TABLE_CHAT_MESSAGE,
				contentValues, "message_id = ?",
				new String[] { String.valueOf(list.get(i).getId()) });
	}

	/**
	 * 更新消息下载状态
	 */
	public void updateChatXiaZaiState(
			MessageEntity messageEntity,
			ContentValues contentValues) {
		userDatabase.update(
				Tables.TableChatMessage.TABLE_CHAT_MESSAGE,
				contentValues, "message_id = ?",
				new String[] { String.valueOf(messageEntity.getId()) });
	}

	/**
	 * 查询消息id之后的消息
	 * @param sendId
	 * @param receiveId
	 * @param isGroupChat
	 * @param mesgeId
	 * @param number
	 * @param noSendList
	 * @return
	 */
	public Cursor queryChatMesgeByIdAfter(String sendId,
			String receiveId, boolean isGroupChat, String mesgeId,
			String number) {
		return userDatabase
				.query(
						Tables.TableChatMessage.TABLE_CHAT_MESSAGE,
						new String[] { "message_id", "message_type",
								"receiver_id", "sender_id", "read_tag",
								"message_content", "message_path",
								"voice_length", "sendstate", "downorupstate",
								"time", "isSend",
								Tables.TableChatMessage.MESSAGE_JSONCOTENT,
								Tables.TableChatMessage.MSG_SERVER_ID,
								TableChatMessage.MSG_SERVER_DELET_STATE
								},
						"message_id in ( select message_id from "
								+ Tables.TableChatMessage.TABLE_CHAT_MESSAGE
								+ " where message_id < ?  and ((sender_id=? and receiver_id=?) or (receiver_id=? and sender_id=?)) ORDER BY message_id desc LIMIT ?)",
						new String[] { mesgeId, sendId, receiveId, sendId,
								receiveId, number }, null, null, null, null);
	}

	/**
	 * 查询历史消息
	 * 
	 */
	public  Cursor chatLiShiMessage(String sendId, String receiveId,
			String number) {
		return userDatabase.query(Tables.TableChatMessage.TABLE_CHAT_MESSAGE,
				new String[] { "message_id", "message_type", "receiver_id",
						"sender_id", "read_tag", "message_content",
						"message_path", "voice_length", "sendstate",
						"downorupstate", "time", "isSend" },
				"sender_id=? and receiver_id=?", new String[] { sendId,
						receiveId }, null, null, "message_id asc", number);
	}

	/**
	 * 查询查询新闻收藏列表
	 * 
	 */
	public  Cursor queryNewShouCangList() {
		return userDatabase.query(
				Tables.TableNewsCollection.TABLE_NEWS_COllECTION, new String[] {
						"news_cllection_id", "news_id", "news_type",
						"news_title", "news_time", "type_title" }, null, null,
				null, null, "news_cllection_id asc");
	}

	/**
	 * 根据新闻id和类型查询新闻是否存在
	 * 
	 */
	public  Cursor queryNewsIdIsExis(Cursor cursor, String newsType,
			String newsId, boolean isExit) {
		return userDatabase.query(
				Tables.TableNewsCollection.TABLE_NEWS_COllECTION,
				new String[] { "news_id" }, "news_type=? and news_id=?",
				new String[] { newsType, newsId }, null, null, null);
	}
	
	

	/**
	 * 添加新闻到收藏
	 * 
	 * @param contentValues
	 * @return
	 */
	public  boolean inserNewToCollection(ContentValues contentValues) {

		return userDatabase.insert(
				Tables.TableNewsCollection.TABLE_NEWS_COllECTION,
				"news_cllection_id", contentValues) != -1;
	}

	/**
	 * 根据收藏id查询收藏内容
	 * 
	 * @param collectionId
	 * @return
	 */
	public  Cursor QueryNewsQueryContent(String collectionId) {
		return userDatabase.query(
				Tables.TableNewsCollection.TABLE_NEWS_COllECTION,
				new String[] { "news_content" }, "news_cllection_id = ?",
				new String[] { collectionId }, null, null, null);
	}

	/**
	 * 根据收藏id删除收藏新闻
	 * 
	 * @param collectionId
	 * @return
	 */
	public  int deleteCollectionIdNews(String collectionId) {
		return userDatabase.delete(
				Tables.TableNewsCollection.TABLE_NEWS_COllECTION,
				"news_cllection_id = ?", new String[] { collectionId });

	}

	/**
	 * 服务器删除状态
	 * @param collection
	 * @return
	 */
	public boolean updateMsgeDeletState(Collection<String> collection){
		
		try {
			userDatabase.beginTransaction();
			for (String id : collection) {
				ContentValues contentValues = new ContentValues();
				contentValues.put(TableChatMessage.MSG_SERVER_DELET_STATE,"1");
				userDatabase.update(
						TableChatMessage.TABLE_CHAT_MESSAGE, 
						contentValues,
						"msg_server_id=?",
						new String[] { id });
			}
			userDatabase.setTransactionSuccessful();
		} finally {
			userDatabase.endTransaction();
		}
		return true;
	}
	
	/**
	 * 根据收藏id删除收藏新闻
	 * @param collectionId
	 * @return
	 */
	public  boolean deleteCollectionToId(List<NewsEntity> list) {
		userDatabase.beginTransaction();
		try {
			for (NewsEntity newsEntity : list) {
				deleteCollectionNews(newsEntity.getCollectionId());
			}
			userDatabase.setTransactionSuccessful();
		} finally {
			userDatabase.endTransaction();
		}
		// ChatUserDatabase.deleteCollectionToId(list);
		return true;
	}

	/**
	 * 根据收藏id删除收藏新闻
	 * 
	 * @param collectionId
	 * @return
	 */
	public  boolean deleteCollectionNews(String collectionId) {
		int value = deleteCollectionIdNews(collectionId);
		return value > 0;
	}

	/**
	 * 删除朋友聊天信息
	 * 
	 * @param id
	 * @return
	 */
	public  boolean deleteFriendChatMessage(String id) {
		return userDatabase.delete(Tables.TableChatMessage.TABLE_CHAT_MESSAGE,
				"message_id = ?", new String[] { id }) > 0;

	}

	/**
	 * 删除所有聊天的记录
	 */
	public  void deleteAllChatMessage() {
		userDatabase.execSQL("delete from "
				+ Tables.TableDoctor.TABLE_VIRTUAL_DOCTOR_MESSAGE);
		userDatabase.execSQL("delete from "
				+ Tables.TableChatMessage.TABLE_CHAT_MESSAGE);
		// sequence 置为0
		userDatabase.execSQL("update sqlite_sequence set seq=0 where name='"
				+ Tables.TableDoctor.TABLE_VIRTUAL_DOCTOR_MESSAGE + "'");
		userDatabase.execSQL("update sqlite_sequence set seq=0 where name='"
				+ Tables.TableChatMessage.TABLE_CHAT_MESSAGE + "'");
		// 释放空间
		userDatabase.execSQL("VACUUM");

	}
	
	public synchronized boolean queryHaveMessageServerId(String serverid){
		Cursor cursor = null;
		try{
			 cursor = userDatabase.query(
						TableChatMessage.TABLE_CHAT_MESSAGE,
						new String[]{TableChatMessage.MSG_SERVER_ID}, 
						"msg_server_id = ?",
						new String[]{serverid},
						null,
						null,
						null,
						null);
				if(cursor != null){
					return cursor.moveToNext();
				}
		}finally{
			if(cursor != null){
				cursor.close();
			}
		}
		return false;
	}

	/**
	 * 查询未读消息 read_tag = 0
	 * @param receiverId
	 * @return
	 */
	public synchronized Cursor queryNoReadMesg(String receiverId) {
		return userDatabase.query(
				TableChatMessage.TABLE_CHAT_MESSAGE,
				new String[] { "message_id", "message_type", "receiver_id",
						"sender_id", "read_tag", "message_content",
						"message_path", "voice_length", "sendstate",
						"downorupstate", "time", "isSend" },
				"read_tag = 0 and receiver_id=?",
				new String[] { receiverId },
				null, null, null, null);

	}

	public  Cursor queryVirtualDoctorChatMessageById(String mesgeId,
			String sendId, String receiveId, String sendId2, String receiveId2,
			String number) {
		return userDatabase
				.query(Tables.TableDoctor.TABLE_VIRTUAL_DOCTOR_MESSAGE,
						new String[] { "message_id", "message_type",
								"receiver_id", "sender_id", "read_tag",
								"message_content", "isSend", "messageCode",
								"messageClass", "retFeatur", "functionId",
								"linkDialog", "ltalkName", "serviceLinkId",
								"serviceLinkName", "largeinfoId", "talkname",
								"time", "sendstate" },
						"message_id in (select message_id from "
								+ Tables.TableDoctor.TABLE_VIRTUAL_DOCTOR_MESSAGE
								+ " where message_id < ?  and ((sender_id=? and receiver_id=?) or (receiver_id=? and sender_id=?)) ORDER BY message_id desc LIMIT ?)",
						new String[] { mesgeId, sendId, receiveId, sendId,
								receiveId, number }, null, null, null, null);

	}

	/**
	 * 查询虚拟医生对话历史消息
	 * 
	 * @param sendId
	 * @param receiveId
	 * @param sendId2
	 * @param receiveId2
	 * @return
	 */
	public  Cursor queryVirtualDoctorChatMesg(String sendId,
			String receiveId, String sendId2, String receiveId2) {
		return userDatabase
				.query(Tables.TableDoctor.TABLE_VIRTUAL_DOCTOR_MESSAGE,
						new String[] { "message_id", "message_type",
								"receiver_id", "sender_id", "read_tag",
								"message_content", "isSend", "messageCode",
								"messageClass", "retFeatur", "functionId",
								"linkDialog", "ltalkName", "serviceLinkId",
								"serviceLinkName", "largeinfoId", "talkname",
								"time" },
						"sender_id=? and receiver_id=? or receiver_id=? and sender_id=?",
						new String[] { sendId, receiveId, sendId, receiveId },
						null, null, null, null);

	}

	/**
	 * 删除单条
	 * 
	 * @param id
	 * @return
	 */
	public  boolean delete(long id) {
		return userDatabase.delete(
				Tables.TableDoctor.TABLE_VIRTUAL_DOCTOR_MESSAGE,
				"message_id = ?", new String[] { String.valueOf(id) }) > 0;

	}

	public  boolean deleteVirtualDoctorChatMesg(
			List<VirtualDoctorEntity> list) {
		userDatabase.beginTransaction();
		try {
			for (VirtualDoctorEntity VirtualDoctorEntity : list) {
				delete(VirtualDoctorEntity.getId());
			}
			userDatabase.setTransactionSuccessful();
		} finally {
			userDatabase.endTransaction();
		}
		return true;
	}

	/**
	 * 更新虚拟医生消息读取状态
	 * 
	 * @param list
	 */
	public  void update(ContentValues contentValues, StringBuffer sql,
			String[] arry) {
		userDatabase.update(Tables.TableDoctor.TABLE_VIRTUAL_DOCTOR_MESSAGE,
				contentValues, sql.toString(), arry);

	}

	/**
	 * 保存虚拟医生对话信息
	 */
	public  void saveVirtualDoctorChatMesg(List<VirtualDoctorEntity> list) {
		userDatabase.beginTransaction();
		try {
			for (VirtualDoctorEntity virtualDoctorEntity : list) {
				insertVirtualDoctorChatMessage(virtualDoctorEntity);
			}
			userDatabase.setTransactionSuccessful();
		} finally {
			userDatabase.endTransaction();
		}
	}

	private  void insertVirtualDoctorChatMessage(
			VirtualDoctorEntity doctorEntity) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(Tables.TableChatMessage.SENDER_ID,
				doctorEntity.getSenderId());
		contentValues.put(Tables.TableChatMessage.RECEIVER_ID,
				doctorEntity.getReceiverId());
		contentValues.put(Tables.TableChatMessage.MESSAGE_TYPE,
				doctorEntity.getType());
		contentValues.put(Tables.TableChatMessage.MESSAGE_CONTENT,
				doctorEntity.getContent());
		contentValues.put(Tables.TableChatMessage.ISSEND,
				doctorEntity.isSendFlag() ? 1 : 0);
		contentValues.put(Tables.TableChatMessage.READ_TAG,
				doctorEntity.getReadTag());
		contentValues.put(Tables.TableChatMessage.MESSAGECODE,
				doctorEntity.getMessageCode());
		contentValues.put(Tables.TableChatMessage.MESSAGECLASS,
				doctorEntity.getMessageClass());
		contentValues.put(Tables.TableChatMessage.RETFEATUR,
				doctorEntity.getRetFeatur());
		contentValues.put(Tables.TableChatMessage.FUNCTIONID,
				doctorEntity.getFunctionId());
		contentValues.put(Tables.TableChatMessage.LINKDIALOG,
				doctorEntity.getLinkDialog());
		contentValues.put(Tables.TableChatMessage.LTALKNAME,
				doctorEntity.getTalkname());
		contentValues.put(Tables.TableChatMessage.SERVICELINKID,
				doctorEntity.getServiceLinkId());
		contentValues.put(Tables.TableChatMessage.SERVICELINKNAME,
				doctorEntity.getServiceLinkName());
		contentValues.put(Tables.TableChatMessage.LARGEINFOID,
				doctorEntity.getLargeinfoId());
		contentValues.put(Tables.TableChatMessage.TALKNAME,
				doctorEntity.getTalkname());
		contentValues.put(Tables.ChatTable.TIME, doctorEntity.getDate());
		contentValues.put(Tables.TableChatMessage.SENDSTATE,
				doctorEntity.getSendState());
		long id = insert(contentValues);
		doctorEntity.setId(id);

	}

	/**
	 * 保存虚拟医生对话信息
	 */
	public  long insert(ContentValues contentValues) {
		long id = userDatabase.insert(
				Tables.TableDoctor.TABLE_VIRTUAL_DOCTOR_MESSAGE, "message_id",
				contentValues);
		return id;
	}

	public  long updateData(String string, ContentValues values,
			String string2, String[] strings) {
		return userDatabase.update(Tables.TableFriend.TABLE_FRIEND, values,
				"id = ?", strings);

	}

	/**
	 * 保存聊天室信息
	 * 
	 * @param string
	 * @param values
	 * @param string2
	 * @param strings
	 * @return
	 */
	public  long saveGroupMesgInfos(String string, ContentValues values,
			String string2, String[] strings) {
		return userDatabase.update(string, values, "id = ?", strings);
	}

	public  Cursor reQuery(String sql, String[] strings) {
		return userDatabase.rawQuery(sql, strings);
	}

	/**
	 * 删除新闻收藏数据
	 * 
	 * @param tablNameNewsConnection
	 * @param string
	 * @param strings
	 * @return
	 */
	public  int deleteIdNews(String tablNameNewsConnection,
			String string, String[] strings) {
		return userDatabase.delete(tablNameNewsConnection,
				Tables.TableNewsCollection.CONNECTION_USERID + " = ? and "
						+ Tables.TableNewsCollection.NEWS_ID + " = ?", strings);
	}

	/**
	 * 收藏新闻
	 * 
	 * @param title
	 *            标题
	 * @param time
	 *            时间
	 * @param content
	 *            新闻内容
	 * @param connectionUserId
	 *            用户id
	 * @param typeCode
	 *            内容类型id
	 * @param contentId
	 *            内容id
	 * @return
	 */
	public synchronized long insertData(String tablNameNewsConnection, String object,
			ContentValues contentValues) {
		return userDatabase.insert(tablNameNewsConnection, null, contentValues);
	}

	public synchronized Cursor queryData(String string, String[] strings,
			String string2, String[] strings2, Object object, Object object2,
			String string3) {
		return userDatabase.query(string, strings, string2, strings2, null,
				null, string3);

	}

	/**
	 * 删除沙龙
	 */
	public synchronized void deleteSalon(String tablNameNewsConnection,
			String string, String[] strings) {
		userDatabase.delete(tablNameNewsConnection,string, strings);
	}

}
